package com.njcs.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.HttpURLConnection;

public class XingeBaidu {
	public XingeBaidu() {
		String strLine;
		int beginIndex, endIndex, idx;
		System.out.println("连接到百度新歌\n");

		try {
			URL url = new URL("http://xinge.baidu.com/");
			HttpURLConnection objHttp = (HttpURLConnection) url
					.openConnection();
			objHttp.setRequestProperty("Connection", "Keep-Alive");
			InputStream objIS = objHttp.getInputStream();
			BufferedReader objReader = new BufferedReader(
					new InputStreamReader(objIS));

			while ((strLine = objReader.readLine()) != null) {
				if ((beginIndex = strLine.indexOf("{sid:")) != -1) {
					if ((idx = strLine.indexOf("al:")) != -1
							&& (endIndex = strLine.indexOf("',ti")) != -1
							&& idx + 4 < endIndex)
						System.out.printf("[唱片集:%s]  ", strLine.substring(
								idx + 4, endIndex));
					if ((idx = strLine.indexOf("ti:")) != -1
							&& (endIndex = strLine.indexOf("',si")) != -1
							&& idx + 4 < endIndex)
						System.out.printf("%s", strLine.substring(idx + 4,
								endIndex));
					if ((idx = strLine.indexOf("si:")) != -1
							&& (endIndex = strLine.indexOf("',cp")) != -1
							&& idx + 4 < endIndex)
						System.out.printf("  [歌手:%s]", strLine.substring(
								idx + 4, endIndex));
					System.out.printf("\n");

					if ((endIndex = strLine.indexOf(".mp3")) != -1) {
						strLine = strLine.substring(beginIndex + 6,
								endIndex + 4);
						getMP3URL("http://xinge.baidu.com/wgns/url/" + strLine);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void getMP3URL(String surl) throws Exception {
		String strLine;
		URL url = new URL(surl);
		HttpURLConnection objHttp = (HttpURLConnection) url.openConnection();

		InputStream objIS = objHttp.getInputStream();
		BufferedReader objReader = new BufferedReader(new InputStreamReader(
				objIS));

		if ((strLine = objReader.readLine()) != null) {
			strLine = "http://xinge.baidu.com" + strLine;
			System.out.println(strLine); // 打印查找到的MP3的真实网址
			// 播放或下载的代码...
			Thread.sleep(500);
		}
		objHttp.disconnect();
		objHttp = null;
		objReader.close();
		objReader = null;
		url = null;
	}

	public static void main(String[] args) {
		new XingeBaidu();
	}
}